// 云函数模板
// 部署：在 cloud-functions/login 文件夹右击选择 “上传并部署”

const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init()
const db = cloud.database()
const ONE_DAY = 24 * 60 * 60 * 1000;

exports.main = async(event, context) => new Promise((resolve, reject) => {
  // 获取 WX Context (微信调用上下文)，包括 OPENID、APPID、及 UNIONID（需满足 UNIONID 获取条件）
  const wxContext = cloud.getWXContext()
  console.log(event, wxContext);
  const needDetail = event.needDetail || false;
  missionMap.clear();
  db.collection('user').doc(wxContext.OPENID).get()
    .then(res => {
      //更新用户登录信息
      db.collection('user').doc(wxContext.OPENID).update({
        data: {
          lastTime: new db.serverDate()
        }
      })

      const userInfo = res.data
      if (!needDetail) {
        resolve({
          openid: wxContext.OPENID,
          err: null,
          created: true,
          userInfo
        })
        return;
      } else {
        //查询详细信息
        // let masterSet = new Set(userInfo.master);
        // let projectSet = new Set(userInfo.project);
        //抓取用户任务
        let dealData = {
          openid: wxContext.OPENID,
          err: null,
          created: true,
          userInfo,
          master: [],
          project: [],
          mission:[]
        }
        const getProjects = new Promise(resolve => {
          db.collection('code').where({
            userId: wxContext.OPENID
          }).field({
            group: true,
            role: true
          }).get().then(res => {
            if (res.data && res.data.length) {
              //区分master与normal
              const masterList = [],
                projectList = [];
              if (!res.data || !res.data.length) {
                resolve();
                return;
              }
              for (const item of res.data) {
                if (item.role === 'master') {
                  masterList.push(item.group)
                } else {
                  projectList.push(item.group)
                }
              }
              Promise.all([
                getProject(masterList).then(master => {
                  dealData.master = master
                }),
                getProject(projectList).then(project => {
                  dealData.project = project
                }),
              ]).then(resolve)
            } else {
              resolve()
            }

          })
        })
        const getMissions = new Promise((resolveMission) => {
          db.collection('mission').where({
            userId: wxContext.OPENID
          }).get().then(missionList => {
            let listWaitForInit = [];
            let listDoing = [];
            let listDone = [];
            for (let item of missionList.data) {
              if (!item.init) {
                listWaitForInit.push(item)
              } else if (item.status === 'done') {
                listDone.push(item)
              } else {
                listDoing.push(item)
              }
            }
            listDone.sort((a, b) => {
              return Date.parse(b.end) - Date.parse(a.end)
            });
            let computeList = [];
            listDoing.forEach(item => {
              //判断任务是否需要计算开始时间
              if (item.front.length) {
                computeList.push(
                  figureOutStartDate(item).then(res => {
                    if (res) {
                      figureOutEndDate(item)
                    }
                  })
                )
              }
            })
            // if (!computeList.length) {
            //   debugger
            //   resolveMission()
            //   return;
            // }
            Promise.all(computeList).then(() => {
              let listHasRange = [],
                listNoRange = [];
              for (const item of listDoing) {
                if (item.end) {
                  listHasRange.push(item)
                } else {
                  listNoRange.push(item);
                }
              }
              listHasRange = listHasRange.sort((a, b) => Date.parse(a.end) - Date.parse(b.end)).sort((a, b) => !a.star && b.star)

              const mission = [...listWaitForInit, ...listHasRange, ...listNoRange, ...listDone]
              return new Promise((resolve2) => {
                const promiseList = [];
                mission.forEach((item, index) => {
                  if (!item.init) {
                    promiseList.push(
                      db.collection('user').doc(item.consignor)
                      .get().then(res => {
                        mission[index].consignorClient = res.data
                      })
                    )
                  } else {
                    // return item;
                  }
                })
                Promise.all(promiseList).then(() => {
                  resolve2(mission)
                })
              })
            }).then(res => {
              debugger
              dealData.mission = res;
              resolveMission()
            })
          })
        })
        //处理任务
        Promise.all(
          [
            getProjects,
            getMissions
          ]
        ).then(() => {
          resolve(dealData)
        }).catch(err => {
          console.log(err)
          reject(err)
        })


      }

    })
    .catch(err => {
      console.log(err);
      const data = {
        _id: wxContext.OPENID,
        userId: wxContext.OPENID,
        inited: false,
        master: [],
        project: [],
        userName: null,
        userColor: null,
        createTime: new Date(),
        lastTime: new Date()
      }
      db.collection('user').add({
        data
      }).then(res => {
        console.log('dbAdd:', res)
        resolve({
          openid: wxContext.OPENID,
          err: null,
          created: true,
          userInfo: data
        })
      }).catch(err => {
        console.log('dbAddErr:', err)
        reject({
          openid: wxContext.OPENID,
          err
        })
      })
    })
})

function getProject(projectList) {
  return new Promise((resolve, reject) => {
    if (projectList.length) {
      const order = db.command.or(projectList.map(item => ({
        _id: item
      })));
      db.collection('group').where(order).get()
        .then(proj => {
          resolve(proj.data.sort((a, b) => {
            projectList.indexOf(a._id) - projectList.indexOf(b._id)
          }))
        }).catch(err => {
          console.log('数据拉取失败', err)
          reject(err)
        })
    } else {
      resolve([])
    }
  })

}

const missionMap = new Map();

function getMissionItem(id) {
  if (missionMap.has(id)) return missionMap.get(id);
  return db.collection('mission').doc(id).get().then(res => {

    missionMap.set(id, res.data)
    return res.data

  })
}
async function figureOutEndDate(item) {
  if (item.end) return item.end;
  else {
    let end = null;
    if (item.front && item.front.length) {
      let startPoint = Date.parse(await figureOutStartDate(item));
      if (startPoint) {
        for (let j = 0; j < item.last; startPoint += ONE_DAY) {
          const tempDate = new Date(startPoint);
          const day = tempDate.getDay();
          //排除周六周日
          if (day !== 0 && day !== 6) {
            j++;
          }
        }
        startPoint -= ONE_DAY;
        item.end = end = new Date(startPoint).toLocaleDateString();
        // console.log('206', end)
      }
    }
    // console.log('任务起始时间', start);
    return end;
  }
}
async function figureOutStartDate(item) {
  if (item.start) return item.start;
  else {
    let start = null;
    if (item.front && item.front.length) {
      for (const id of item.front) {
        const targetMission = await getMissionItem(id);
        const targetDateObject = await figureOutEndDate(targetMission);

        let targetDate;
        if (targetDateObject) {
          targetDate = Date.parse(targetDateObject) + ONE_DAY;
          if (!start || start < targetDate) {
            start = targetDate;
          }
        }

      }
      // console.log('230', start)
      if (start) item.start = start = new Date(start).toLocaleDateString();
    }
    // console.log('任务起始时间', start);
    return start;
  }
}